package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"prod-stat-mgr/cache"
	"prod-stat-mgr/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	content := c.PostForm("content")
	num, _ := strconv.Atoi(c.PostForm("num"))
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	typesId, _ := strconv.Atoi(c.PostForm("types_id"))

	if name == "" || content == "" || num == 0 || userId == 0 || typesId == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := models.Prod{
		Name:     name,
		Content:  content,
		Num:      num,
		UserID:   userId,
		TypesID:  typesId,
		XiaCount: 0,
	}
	tx := models.DB.Begin()
	err := tx.Create(&data).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	redis_key := "add_prod_" + strconv.Itoa(int(data.ID))
	var prod models.Prod
	tx.Where("id = ?", data.ID).First(&prod)
	jsonData, _ := json.Marshal(&prod)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	tx.Commit()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func List(c *gin.Context) {
	var prod []models.Prod

	redis_key := "list_prod"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&prod)
		jsonData, _ := json.Marshal(&prod)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &prod)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": prod,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var prod models.Prod

	redis_key := "detail_prod" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).First(&prod)
		jsonData, _ := json.Marshal(&prod)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &prod)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": prod,
	})
	return
}
func Xia(c *gin.Context) {
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	prodId, _ := strconv.Atoi(c.PostForm("prod_id"))

	var xia models.Xia
	err := models.DB.Where("user_id = ? && prod_id = ?", userId, prodId).First(&xia).Error
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复下载",
		})
		return
	}

	xia = models.Xia{
		UserID: userId,
		ProdID: prodId,
	}
	err = models.DB.Create(&xia).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "下载添加失败",
		})
		return
	}
	var prod models.Prod
	err = models.DB.Where("id = ?", prodId).First(&prod).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不存在",
		})
		return
	}
	prod.XiaCount++
	err = models.DB.Save(&prod).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "下载失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "下载成功",
	})
	return
}
